<template>
  <div class="pagination">
    <!-- 当前页码为1不能点 -->
    <button :disabled="pageNo == 1" @click="$emit('getPageNo',pageNo-1)">上一页</button>
    <button v-if="startNumAndendNum.start >1" @click="$emit('getPageNo',1)" :class="{active:pageNo == 1}">1</button>
    <button v-if="startNumAndendNum.start>2">···</button>


      <!-- v-for 和v-if不能连用 -->
    <span v-for="(page, index) in startNumAndendNum.end" :key="index">
      <button v-if="page >= startNumAndendNum.start"  @click="$emit('getPageNo',page)" :class="{active:pageNo == page}">
        {{ page }}
      </button>
    </span>

    <button v-if="startNumAndendNum.end < totalPage-1">···</button>
    <button v-if="startNumAndendNum.end< totalPage" @click="$emit('getPageNo',totalPage)">{{ totalPage }}</button>
    <button :disabled="pageNo == totalPage" @click="$emit('getPageNo',pageNo+1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "pageSize", "total", "continuse"],
  computed: {
    //总页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    startNumAndendNum() {
      const { continuse, pageNo, totalPage } = this;
      let start = 0,
        end = 0;
      // //连续页码为5,但是总页数小于5的情况 最后一位就应该是总页数
      if (continuse > totalPage) {
        (start = 1), (end = totalPage);
      } else {
        //
        start = pageNo - parseInt(continuse / 2);
        end = pageNo + parseInt(continuse / 2);

        // pageNo 为1的时候 或者pageNo<continuse/2的时候 start为负数
        if (start < 1) {
          start = 1;
          end = continuse;
        }
        //同理。处理end
        if (end > totalPage) {
          end = totalPage;
          start = totalPage - continuse + 1;
        }
      }
      //计算连续页码数的第一个数字，和最后一个数字
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>